package com.javasm.domain;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author：MoDebing
 * @Version：1.0
 * @Date：2022-09-01-17:11
 * @Description: 实现安全框架的UserDetails接口用于封装并返回用户信息
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    // 定义我们自己的user对象
    private User user;

    // 权限String对象
    private List<String> permissions;

    // 因为不需要把这个权限的信息存入到redis当中，因此不需要序列化该成员变量,redis也不支持序列化该类型
    @JSONField(serialize = false)
    private Set<SimpleGrantedAuthority> authorities;

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 把permissions中类型的权限封装成GrantedAuthority实现类SimpleGrantedAuthority对象

        //Set<SimpleGrantedAuthority> authoritySet = new HashSet<>(); //使用set是因为可以去重
        //for (String permission : permissions) {
        //    authoritySet.add(new SimpleGrantedAuthority(permission));
        //}
        //return authoritySet;


        //方法二:把permissionSet
        if (CollectionUtils.isEmpty(authorities)){
            authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
        }
        return authorities;
    }

    /**
     * 获取用户密码
     *
     * @return String
     */
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    /**
     * 获取用户名
     *
     * @return String
     */
    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
